package com.gz.moreaseManager.core.base;

import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @文件名: BaseController
 * @版权:Copyright 2018-2020版权所有：ganz
 * @描述: 封装常用方法
 * @修改人: ganzheng
 * @修改时间: 9:55
 * @修改内容:新增
 */
public class BaseController {


    /**
     * 根据上传文件返回成功后的路径
     * @param file
     * @return
     * @throws Exception
     */
    protected String uploadFile(MultipartFile file) {
        if( !file.isEmpty()) {
            //获取项目路径
            ApplicationHome applicationHome = new ApplicationHome();
            //判断文件存储路径是否有文件
            File homePath = new File(applicationHome.getDir().getPath() + Constants.SYS_CONFIG_UPLOAD_PATH);
            if (!homePath.exists()) homePath.mkdir();
            try {
                //重新生成文件名称
                String fileName = UtilTool.getNewFileName(file.getOriginalFilename());
                File uploadFile = new File(homePath.getPath() + "/" + fileName);
                file.transferTo(uploadFile);
                return Constants.SYS_CONFIG_UPLOAD_URL + fileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
